from gettext import gettext as _
import gettext
import gedit
import gtk
import gobject
import pickle
import pprint
import twitter
import bitly  

class TwitterPluginHelper(object):
    def __init__(self, window):
        self._window = window
       # self._plugin = plugin
        self._build_logpanel(window)
        
    def update_ui(self):
        # Called whenever the window has been updated (active tab
        # changed, etc.)
        pass
        
    def _build_logpanel(self,window):
        panel = self._window.get_bottom_panel()
        self.box = gtk.VBox(False,0)
        self.messageLabel = gtk.Label("What are you doing ?")
        self.box2 = gtk.HBox(False,0)
        self.tweetLabel= gtk.Label("Last Message:")
        self.lastTweet = gtk.Label("")
        self.box.pack_start(self.messageLabel, False, False, 0)
        self.box2.pack_start(self.tweetLabel,False,False,0)
        self.box2.pack_start(self.lastTweet,False,False,0)
        self.box.pack_start(self.box2, False, False, 0)
      #  self.box.pack_start(self.messageLabel, True, True, 0)
        self.box1 = gtk.HBox(False, 0)
        self.tweet = gtk.Entry()
        self.tweet.set_max_length(140)
        self.box1.pack_start(self.tweet, True, True, 0)
        self.button = gtk.Button("Tweet")
        self.button.connect("clicked", self._tweet, None)
        self.box1.pack_start(self.button, False, True, 0)
        image = gtk.Image()
        self.box.pack_start(self.box1, True, True, 0)
        panel.add_item(self.box, "Twitter", image)
        self.box.show_all()        
        self.box1.show_all()
    
    def deactivate(self):
        pannel = self._window.get_bottom_panel()
        pannel.remove_item(self.box) 
    
    def _tweet(self,widget,info):
        message = self.tweet.get_text()
        apil = bitly.Api(login='geditplug', apikey='R_e8cfad853ccee11add41ab049c5bf5eb')
        pkl_file = open('.gnome2/gedit/plugins/data.pkl', 'rb')
        data = pickle.load(pkl_file)
        pkl_file.close()
        username=data["username"]
        password=data["password"]
        api = twitter.Api(username,password)
        short = str(message)
        if "http://" in short:
           a = short.split()
           b = len(a)
           for i in range(0, b):
               c = a[i].find('http://')
               if c != -1:       
                  mes = apil.shorten(a[i])
                  mess = mes.join(short.split(a[i]))
                  status = api.PostUpdate(mess)
	       else:
		  print "keep trying"
	       
	    
        elif "https://" in short:
             a = short.split()
             b = len(a)
             for i in range(0, b):
               c = a[i].find('https://')
               if c != -1:       
                  mes = apil.shorten(a[i])
                  mess = mes.join(short.split(a[i]))
                  status = api.PostUpdate(mess)
	       else:
		  print "keep trying" 
        elif "www" in short:
             a = short.split()
             b = len(a)
             for i in range(0, b):
               c = a[i].find('www')
               if c != -1:     
                  mes = apil.shorten(a[i])
                  mess = mes.join(short.split(a[i]))
                  status = api.PostUpdate(mess)
	       else:
		  print "keep trying" 
        else:
 	   status = api.PostUpdate(short)	
 	   
        self.tweet.set_text('')
        self.lastTweet.set_text(message)
      
        
class TwitterPlugin(gedit.Plugin):
    WINDOW_DATA_KEY = "GeditPluginWindowData"
    
    def __init__(self):
        gedit.Plugin.__init__(self)

    def activate(self, window):
        helper = TwitterPluginHelper(window)
        window.set_data(self.WINDOW_DATA_KEY, helper)	
  	
    def deactivate(self, window):
        window.get_data(self.WINDOW_DATA_KEY).deactivate()
        window.set_data(self.WINDOW_DATA_KEY, None)


    def update_ui(self, window):
        window.get_data(self.WINDOW_DATA_KEY).update_ui()
        
        
    def is_configurable(self):
        return True

    def create_configure_dialog(self):
        pkl_file = open('.gnome2/gedit/plugins/data.pkl', 'rb')
        data = pickle.load(pkl_file)
        pkl_file.close()
        buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        dialog = gtk.Dialog("Twitter Plugin Configuration", None,0,buttons)
        usernameLabel = gtk.Label("Username")
        self.nameEntry = gtk.Entry()
        self.nameEntry.set_max_length(50)
        self.nameEntry.set_text(data["username"])
        pwLabel = gtk.Label("Password")
        self.pwEntry = gtk.Entry()
        self.pwEntry.set_max_length(50)
        self.pwEntry.set_text(data["password"])
        self.pwEntry.set_visibility(False)
        table = gtk.Table(2, 2, True)
        table.attach(usernameLabel, 0, 1, 0, 1)
        table.attach(self.nameEntry, 1, 2, 0, 1)
        table.attach(pwLabel, 0, 1, 1, 2)
        table.attach(self.pwEntry, 1, 2, 1, 2)
        self.savePassCheck = gtk.CheckButton("Remember Username/Password")
        self.label = gtk.Label("Enter your user name and password")
        self.label.set_selectable(True)
        self.label.set_line_wrap(True)
        dialog.vbox.pack_start(self.label, True, True, 10)
        dialog.vbox.pack_start(table, True, True, 0)
        dialog.vbox.pack_start(self.savePassCheck, True, True, 0)
        dialog.show_all()
        dialog.connect("response", self.on_response)
        self.dialog = dialog
        return dialog
        
    def on_response(self, dialog, response_id):
      if (response_id == gtk.RESPONSE_OK):
        #get the login details, etc:
        self.username = self.nameEntry.get_text()
        self.password = self.pwEntry.get_text()
        data = {'username': self.username, 'password': self.password}
        output = open('.gnome2/gedit/plugins/data.pkl', 'wb')
        pickle.dump(data, output)
        output.close()
        self.label.set_text("Saving Data...")
        
        

       
      elif (response_id == gtk.RESPONSE_CANCEL):
        self.dialog.destroy()
      else:
        self.label.set_text("How did that even happen?")
